import axios from 'axios';
import moment from 'moment';

// 1. 初始状态.
const state = () => ({
    threads: [],
});

// 2. 计算属性.
const getters = {};

// 3. 异步修改.
const actions = {
    loadThreads({ state }, iid) {
        return axios.get(`/jvm/getThreadDetails/${iid}`).then((data) => {
            // 3.1. 存储新生线程.
            const newThread = [];

            // 3.2. 尝试更新原有线程.
            data.data.forEach((item) => {
                const idx = state.threads.findIndex(
                    (v) => v.threadName === item.threadName && v.threadStatus === item.threadStatus,
                );

                if (idx === -1) {
                    newThread.push(item);

                    return;
                }

                state.threads[idx].time[1] = moment(item.timeline * 1000).format('YYYY-MM-DD HH:mm:ss');
            });

            // 3.3. 处理新生线程.
            newThread.forEach((v) => {
                const time = moment(v.timeline * 1000).format('YYYY-MM-DD HH:mm:ss');

                state.threads.push({
                    threadName: v.threadName,
                    threadStatus: v.threadStatus,
                    time: [time, time],
                });
            });
        });
    },
};

// 4. 同步修改.
const mutations = {
    clearData(state) {
        state.threads = [];
    },
};

// 5. 模块导出.
export default {
    namespaced: true,
    state,
    getters,
    actions,
    mutations,
};
